<template>
  <div style="background: #EEEEEE7F; min-height: 100vh">
    <van-nav-bar
        title="仪器预约"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />

    <van-pull-refresh :model-value="loading" @refresh="refreshAll">
      <van-space direction="vertical" fill>

        <InstrumentCard :instrument="instrumentRef"/>

        <!-- 预约信息 -->
        <van-cell-group inset>
          <van-cell  style="font-size: 18px; font-weight: bold;" >
            <template #title>预约信息</template>
          </van-cell>
          <van-cell
              title="选择预约日期"
              :value="selectedDate"
              @click="showCalendar = true"
          />
          <van-calendar
              v-model:show="showCalendar"
              @confirm="onDateConfirm"
              :min-date="new Date()"
          />
          <van-cell title="预约时间段" />
          <TimeSlot
              :timeSlots="timeSlots"
              :selectedTimeSlotId="selectedTimeSlotId"
              @select="handleTimeSlotSelect"
          />
        </van-cell-group>

        <!-- 审核人 -->
        <van-cell-group inset>
          <van-cell style="--van-cell-horizontal-padding: 8px">
            <van-field
                v-model="selectedReviewerText"
                is-link
                label="审核人"
                placeholder="选择审核人"
                readonly
                @click="showReviewerPicker = true"
            />
          </van-cell>
          <van-popup v-model:show="showReviewerPicker" position="bottom" round>
            <van-picker
                :columns="reviewerOptions"
                @cancel="showReviewerPicker = false"
                @confirm="onReviewerConfirm"
            />
          </van-popup>
        </van-cell-group>

        <!-- 积分 -->
        <van-cell-group inset>
          <van-cell
              title="本次扣除积分"
              :value="deductPoints"
              style="--van-cell-value-color: #46afff"
          />
          <van-cell title="剩余积分" :value="userPoints" />
        </van-cell-group>

        <!-- 提交按钮 -->
        <div style="width: auto; margin: 0 16px 8px 16px">
          <van-button round type="primary" block @click="reservation">
            立即预约
          </van-button>
        </div>
      </van-space>
    </van-pull-refresh>
  </div>
</template>

<style scoped>
</style>


<script setup lang="ts">
import router from "@/apps/client/router.js";
import TimeSlot from "@/apps/client/components/TimeSlot.vue";
import {ref, onMounted, computed} from "vue";
import {
  createInstrumentReservation,
  getInstrumentInfo,
  getInstrumentTimeSlots
} from "@/apps/client/utils/instrumentApi.js";
import { getUserInfo } from "@/apps/client/utils/userApi.js";
import {
  closeToast, showDialog,
  showLoadingToast,
  showNotify,
  showToast
} from "vant";
import { formatDateToYMD } from "@/apps/utils/DateUtil.js";
import InstrumentCard from "@/apps/client/components/instrumentCard.vue";

// 路由返回
const onClickLeft = () => router.back();

const instrumentRoomNumber = ref();
const instrumentSubType = ref();

// 日期选择器
const showCalendar = ref(false);
const selectedDate = ref(formatDateToYMD(new Date(Date.now())));


// 审核人 Picker 控制
const showReviewerPicker = ref(false);
const reviewerOptions = ref<{ text: string; value: number }[]>([]);
const selectedReviewerText = ref('');
let selectedReviewer: { text: string; value: number } | null = null;

// 时间段列表与选中项
const timeSlots = ref<any[]>([]);
const selectedTimeSlotId = ref<number | null>(null);

// 仪器信息与积分
const instrumentId = sessionStorage.getItem("selectInstrumentId");
const instrumentRef = ref<{ name?: string; imgName?: string; pointsCost?: number }>({});
const userPoints = ref('');
const deductPoints = ref('');

// 加载状态
const loading = ref(false);

// 日期确认回调
const onDateConfirm = (selectDate: Date) => {
  selectedDate.value = formatDateToYMD(selectDate);
  showCalendar.value = false;
  selectedTimeSlotId.value = null;
  fetchTimeSlots();
};

// 审核人选择回调
const onReviewerConfirm = ({ selectedOptions }: any) => {
  showReviewerPicker.value = false;
  selectedReviewer = selectedOptions[0];
  selectedReviewerText.value = selectedReviewer.text;
};

// 选择时间段回调
const handleTimeSlotSelect = (slot: any) => {
  selectedTimeSlotId.value = slot.id;
};

// 提交预约
const reservation = () => {
  if (!selectedTimeSlotId.value) {
    showNotify({ message: '请选择预约时间段' });
    return;
  }

  if (!selectedReviewer) {
    showNotify({ message: '请选择审核人' });
    return;
  }

  showLoadingToast({ message: '提交中...', forbidClick: true, duration: 0 });

  const payload = {
    instrumentId,
    date: selectedDate.value,
    timeSlotId: selectedTimeSlotId.value,
    reviewerId: selectedReviewer.value
  };

  createInstrumentReservation(payload)
      .then((body) => {
        if (body.code === 200) {
          showNotify({ type: "success", message: "预约申请成功" });
          refreshAll();
        } else {
          showNotify({ message: body.msg });
        }
      })
      .catch((err) => {
        console.error('预约失败:', err);
        showToast(err.response?.data?.msg || err.message || '预约申请失败，请稍后重试');
      })
      .finally(() => {
        closeToast();
      });
};

// 初始化函数
async function init() {
  await fetchInstrumentInfo();
  await fetchTimeSlots();
}

// 获取仪器详情
async function fetchInstrumentInfo() {
  const body = await getInstrumentInfo(instrumentId);
  if (body.code !== 200) {
    showDialog({
      title: "错误",
      message: body.msg,
    }).then(() => router.back());
    return;
  }

  const instrument = body.data.instrument;

  instrumentRoomNumber.value = instrument["room"]["number"]
  instrumentSubType.value = instrument["subType"]["name"]
  instrumentRef.value = instrument;

  reviewerOptions.value = body.data.reviewer.map((item: any) => ({
    text: item.name,
    value: item.id
  }));

  const currentPoints = Number(sessionStorage.getItem("points"));
  userPoints.value = `${currentPoints - instrument.pointsCost}积分`;
  deductPoints.value = `${instrument.pointsCost}积分`;
}

// 获取时间段
async function fetchTimeSlots() {
  const body = await getInstrumentTimeSlots({
    instrumentId,
    date: selectedDate.value
  });
  timeSlots.value = body.data;
}

// 刷新所有
async function refreshAll() {
  loading.value = true;
  await fetchTimeSlots();
  const user = await getUserInfo();
  sessionStorage.setItem("points", user.data.points);
  userPoints.value = `${user.data.points}积分`;
  loading.value = false;
}

onMounted(init);
</script>

